package com.steam.xbcc.listener;

import com.alibaba.fastjson.JSON;
import com.steam.xbcc.domain.CourseOrder;
import com.steam.xbcc.dto.PayDto;
import com.steam.xbcc.service.ICourseOrderService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQTransactionListener(txProducerGroup = "tx-course-order-group")
public class CourseOrderTxListener implements RocketMQLocalTransactionListener {

    @Autowired
    private ICourseOrderService courseOrderService;

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object arg) {
        try {
            log.info("课程下单执行本地事务开始！");
            if (arg == null){
                return RocketMQLocalTransactionState.ROLLBACK; // 不消费消息
            }
            CourseOrder courseOrder = JSON.parseObject(arg.toString(), CourseOrder.class);
            // 为了防止用户操作异常，同时进来导致线程不安全，那么我们可以加个同步锁
            synchronized (courseOrder.getOrderNo()){
                // 防止已经保存成功了
                if (courseOrderService.selectByOrderNo(courseOrder.getOrderNo()) != null){
                    log.info("课程订单已存在！");
                    return RocketMQLocalTransactionState.ROLLBACK;
                }
                courseOrderService.saveCourseOrderAndCourseOrderItems(courseOrder);
            }
            log.info("课程下单执行本地事务结束！");
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("课程下单执行本地事务异常");
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
 
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            byte[] bytes = (byte[]) message.getPayload();
            // 2.转换为我们想要的对象
            String paramStr = new String(bytes, StandardCharsets.UTF_8);
            PayDto payDto = JSON.parseObject(paramStr, PayDto.class);
            if (payDto == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(payDto.getOrderNo());
            if (courseOrder == null){
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            return RocketMQLocalTransactionState.COMMIT;
        } catch (Exception e) {
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }
}
